import {Injectable} from '@angular/core';
import {Http,HttpModule,Headers,Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {User} from '../model/user';
import 'rxjs/add/operator/map';

@Injectable()
export class UserLoginService{
    public loginUrl='mock-data/user-login.json';
    public subject:Subject<User>=new Subject<User>();
    public get currentUser():Observable<User>{
        return this.subject.asObservable();
        }
    /*
     * 用于测试数组reduce方法
     * @memberof UserLoginService
     */
    public arr = ["apple","orange","apple","orange","pear","orange"];

    constructor(
        public http:Http
    ){}

    /**
     * 登录
     * user 登录用户信息,  实际请求后台的话是需要将user的信息传递到后台的，本例测试用的get请求本地文件json数据，未传递参数
     * @memberof UserLoginService
     */
    public login(user:User){
        return this.http.get(this.loginUrl)
               .map((response:Response)=>{
                    let getUser=response.json();
                    //模拟后台返回结果
                    if(user.userName==getUser.userName){
                        console.log("用户名正确");
                        window.localStorage.setItem("currentUser",JSON.stringify(getUser));
                    }
                    else{
                        getUser.msg="请用admin登录";
                    }
                    return getUser;
                });            
    }

    /**
     * 退出登录
     * 
     * @memberof UserLoginService
     */
    public logOut(){
        localStorage.removeItem("currentUser");
        this.subject.next(Object.assign({}));
    }

    public triggerNextValue(obj:any){
        this.subject.next(Object.assign({},obj));
    }

    /**
     * 数组reduce方法的测试
     * reduce(callback, initialValue)
     */
    public getWordCnt(){      
        //prev是从数组中第一个元素开始的，next是第二个元素。但是传入initialValue后，prev就是initialValue，next则变成第一个元素
        let newa= this.arr.reduce(function(prev,next){      
          prev[next] = (prev[next] + 1) || 1;
          return prev;
        },{});
        return newa;
      }
      //未传入initvalue时
      public noPassValue(){
        let arr2=this.arr.reduce(function(prev,next){
          console.log("prev:",prev);
          console.log("next:",next);   
          return prev + " " +next;
        });
        return arr2;
      }
}